package Action;

import java.util.HashMap;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import Dao.UserDao;
import Form.User;

public class LoginAction extends SimpleFormController {
	private String fail_view;
	private String success_view;
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setFail_view(String fail_view) {
		this.fail_view = fail_view;
	}

	public void setSuccess_view(String success_view) {
		this.success_view = success_view;
	}

	// @Override
	// @RequestMapping(value="login", method=RequestMethod.POST)
	protected ModelAndView onSubmit(Object command, BindException errors)
			throws Exception {
		User user = (User) command;
		User loginUser = login(user);
		if (loginUser != null) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("user", loginUser);
			return new ModelAndView(success_view, map);
		} else {
			return new ModelAndView(fail_view);
		}
	}

	private User login(User user) throws Exception {
		User loginUser;
		try {
			loginUser = userDao.getUserByUsername(user.getUsername());
		} catch (Exception e) {
			throw e;
		}
		if (loginUser != null) {
			if (loginUser.getPassword().equalsIgnoreCase(user.getPassword())
					&& loginUser.getUsername().equalsIgnoreCase(user.getUsername()))
				
				return loginUser;
			else
				return null;
		} else
			return null;
	}

}
